import React, {useEffect, useState, useMemo} from 'react';
import {connect, Dispatch} from 'umi';
import {Avatar, List, Select} from 'antd';
import {ConnectState, IResponse} from "@/models/connect";
import {CHART_TYPE_NAMES} from "@/components/Charts/ChartTypes";
import {IProject} from "@/pages/data";

const {Option} = Select

interface IProps {
  dispatch: Dispatch;
  widgetList: any[]
  projects: IProject[]
}

const WidgetList: React.FC<IProps> = (props) => {
  const {dispatch, widgetList, projects} = props

  const [currentProjectId, setCurrentProjectId] = useState<any>(null);

  useEffect(() => {
    window.postMessage(JSON.stringify({zzzzzzz:"SET",}),'https://datav.zytest.net');
    dispatch({
      type: 'project/fetchProjects',
      callback: (res: IResponse) => {
        if (res && res.payload) {
          const projectList: IProject[] = res.payload
          if (res.payload.length > 0) {
            setCurrentProjectId(projectList[0].id)
            dispatch({
              type: 'widgetIndex/fetchWidgets',
              payload: {projectId: projectList[0].id}
            })

          }
        }

      }
    })

  }, [])
  const onChange = (v: any) => {
    setCurrentProjectId(v)
    dispatch({
      type: 'widgetIndex/fetchWidgets',
      payload: {projectId: v}
    })
  }
  let projectSelect = projects && projects.length>0 ? (<Select style={{width: 200}} defaultValue={projects[0].id}
                                          onChange={onChange}>
      {projects.map(p => {
        return <Option value={p.id}>{p.name}</Option>
      })}
    </Select>)
    :
    null
  return (
    <div style={{padding: "10px"}}>
      {projectSelect}
      <List
        itemLayout="horizontal"
        dataSource={widgetList}
        renderItem={item => {
          const {name, description} = item
          const config = JSON.parse(item.config)
          const {selectedChart} = config
          return (
            <List.Item
              actions={[<a key="list-loadmore-edit">关联指标</a>, <a key="list-loadmore-more">编辑</a>]}
            >
              <List.Item.Meta
                avatar={<Avatar src={CHART_TYPE_NAMES[selectedChart]}/>}
                title={name}
                description={description}
              />
            </List.Item>
          )
        }}
      />
    </div>

  )
}
export default connect(({widgetIndex, project}: ConnectState) => ({
  widgetList: widgetIndex.widgetList,
  projects: project.projects
}))(WidgetList);
